#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年3月8日

@author: Administrator
'''
from common.decorators import login_required
from django.db.models.query_utils import Q
from django.http.response import HttpResponse
from django.template.response import TemplateResponse
from funcresource import settings
from funcresource.decorators import user_funcresource
from funcresource.models import Resource
import copy
import ujson as json


@login_required
@user_funcresource
def index(request, template="funcresource/admin/resource/resourcelist.html"):
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    return TemplateResponse(request, template, rsp_data)
    
@login_required
def list(request):
    """
        func:
                               资源列表
        parameters:
            start:开始下标
            length:每页展示个数
            search[value]:搜索关键字
            columns[4][search][value]:状态
            draw:渲染次数
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = []
    start = int(request.POST['start'])
    length = int(request.POST['length'])
    keyword = request.POST["search[value]"]
    state = request.POST["columns[4][search][value]"]
    state = '' if state == '' else state[1:-1]
    draw = request.POST['draw']
    q = Q()
    if keyword:
        q.add(Q(**{"name__icontains": keyword}), Q.OR)
    if state:
        q.add(Q(**{"state": state}), Q.AND)
    
    count = Resource.objects.filter(q).count()
    resources = Resource.objects.filter(q)[start:start + length]
    for resource in resources:
        record = {
            "id":resource.id,
            "name":resource.name,
            "parent_name":resource.parent.name if resource.parent else "",
            "parent_id":resource.parent.id if resource.parent else "",
            "icon_id":resource.icon.id if resource.icon else "",
            "icon_name":resource.icon.name if resource.icon else "",
            "icon_css":resource.icon.css_class if resource.icon else "",
            "url":resource.url,
            "remark":resource.remark,
            "state":resource.state,
            "state_desc":settings.get_state_desc(resource.state) if resource.state != 1 else u"已停用",
        }
        rsp_data["data"].append(record)
    rsp_data["recordsTotal"] = count
    rsp_data["recordsFiltered"] = count
    rsp_data["draw"] = draw
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def parent_list(request):
    """
        func:
                              父节点集合
        parameters:
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = {}
    rsp_data["data"]["resources"] = []
    resources = Resource.objects.filter(state=settings.StateEnum.VALID)
    for resource in resources:
        record = {
            "id":resource.id,
            "name":resource.name,
        }
        rsp_data["data"]["resources"].append(record)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def save(request):
    """
        func:
                            保存/修改
        parameters:
            resource_id:id
            name:资源名称
            url:资源路径
            parent_id:父节点
            icon_id:资源图标
            remark:资源备注
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    resource_id = request.POST.get("resource_id", "")
    name = request.POST["name"]
    url = request.POST["url"]
    parent_id = request.POST["parent_id"]
    icon_id = request.POST["icon_id"]
    remark = request.POST["remark"]
    if resource_id:
        try:
            resource = Resource.objects.get(id=resource_id)
        except Resource.DoesNotExist:
            rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
            return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    else:
        resource = Resource()
    resource.name = name
    resource.url = url if url else u"javascript:viod(0);"
    if parent_id:
        resource.parent_id = parent_id 
    else:
        resource.parent = None
    if icon_id:
        resource.icon_id = icon_id 
    else:
        resource.icon = None 
    resource.remark = remark
    resource.save()
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def delete(request):
    """
        func:
                                删除
        parameters:
            resource_ids:id集合
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    #获取并赋值
    resource_ids = request.POST["resource_ids"]
    if resource_ids:
        resource_ids = resource_ids.split(",")
    Resource.objects.filter(id__in=resource_ids).update(state=settings.StateEnum.DELETED)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def stop(request):
    """
        func:
                                停用
        parameters:
            resource_ids:id集合
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    #获取并赋值
    resource_ids = request.POST["resource_ids"]
    if resource_ids:
        resource_ids = resource_ids.split(",")
    Resource.objects.filter(id__in=resource_ids, state=settings.StateEnum.VALID).update(state=settings.StateEnum.TEMPORARY)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def enable(request):
    """
        func:
                                启用
        parameters:
            resource_ids:id集合
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    #获取并赋值
    resource_ids = request.POST["resource_ids"]
    if resource_ids:
        resource_ids = resource_ids.split(",")
    Resource.objects.filter(id__in=resource_ids, state__in=[settings.StateEnum.TEMPORARY, settings.StateEnum.DELETED]).update(state=settings.StateEnum.VALID)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
